<?php

namespace app\api\model;

use app\admin\model\Cate;
use app\admin\model\vip\Card;
use think\Model;

/**
 * Scenic
 */
class HitScenic extends Model
{
    // 表名
    protected $name = 'hit_scenic';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    protected $append = [
        'VipCardName',
    ];






    public function getVipCardNameAttr($value, $row): array
    {
        return Card::whereIn('id', $row['vip_card_ids'])->column('name');
    }

    protected static function onAfterInsert($model): void
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    public function getRmScenic($params) {
        $member_id = $params['member_id'] ?? null;
        $user_vip = 0;
        $search = $params['search'] ?? '';

        // 查询用户VIP卡信息（如果存在）
        if ($member_id) {
            $user_vip = (new MemberVipCard())->getMemberVipCardId($member_id,1);
        }

        $map[] = ['rm.status','=',1];
        $map[] = ['s.status','=',1];
        if($search){
            $map[] = ['s.name','like',"%".$search.'%'];
        }

        // 查询景区列表并处理数据
        $list = self::alias('rm')
            ->join('scenic s', 's.id = rm.scenic_id')
            ->join('cate c','c.id = s.cate_id')
            ->where($map)
            ->field('rm.scenic_id, s.name, s.cover, s.scenic_des, s.address, 
            s.vip_card_ids, s.normal_price, s.vip_price,s.city_name,c.name as cate_name')
            ->order('rm.weigh DESC')
            ->paginate(10)
            ->toArray();

        if ($list['total'] == 0) return api_message($list);

        // 处理每个景区的数据
        foreach ($list['data'] as &$val) {
            $val['cover'] = full_url($val['cover']);
//            $vip_card_ids = explode(',', $val['vip_card_ids']);
//            $val['price'] = in_array($user_vip, $vip_card_ids) ? $val['vip_price'] : '';
//            $val['price'] = $val['price'] > 0 ? $val['price'] : '';
//            unset($val['vip_price'], $val['normal_price'], $val['vip_card_ids']);
        }

        return api_message($list);
    }
}
